<script setup lang="ts">
import { computed, h, onMounted, ref } from 'vue'
import dayjs from 'dayjs'
import { storeToRefs } from 'pinia'
import { Modal, message } from 'ant-design-vue'
import { CheckCircleOutlined, EditOutlined } from '@ant-design/icons-vue'
import { useUserStore } from '~/stores/user'
import { getRegistrationDetailApi, getRegistrationsApi, sendSmsCodeApi, updateRegistrationApi } from '~/api/common/login'

const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)

const loading = ref(true)
const latestRegistration = ref<any>(null)
const loadingFailed = ref(false)
const editingField = ref<string | null>(null)
const editForm = ref<any>({})
const editLoading = ref(false)
const smsCodeCountdown = ref(0)
const smsCodeLoading = ref(false)
const emailCodeCountdown = ref(0)
const emailCodeLoading = ref(false)


const displayName = computed(() => {
  const detailName = latestRegistration.value?.username
  const storeName = userInfo.value?.username || userInfo.value?.nickname
  return detailName || storeName || '-'
})

const displayCompany = computed(() => {
  return (
    latestRegistration.value?.company_name
    || userInfo.value?.userCompany
    || '-'
  )
})

const displayPhone = computed(() => {
  return latestRegistration.value?.phone || userInfo.value?.userPhone || '-'
})

const displayEmail = computed(() => {
  const email = latestRegistration.value?.email
  return email && email.trim() !== '' ? email : '-'
})

const baseInfoList = computed(() => {
  const list = [
    {
      key: 'username',
      label: '中文姓名',
      value: displayName.value,
      editable: true,
      field: 'username',
    },
    {
      key: 'phone',
      label: '手机号码',
      value: displayPhone.value,
      editable: true,
      field: 'phone',
    },
    {
      key: 'email',
      label: '电子邮箱',
      value: displayEmail.value,
      editable: true,
      field: 'email',
    },
    {
      key: 'company',
      label: '工作单位',
      value:
        latestRegistration.value?.company_name
        || userInfo.value?.userCompany
        || '-',
      editable: true,
      field: 'company_name',
    },
    {
      key: 'address',
      label: '联系地址',
      value:
        latestRegistration.value?.address
        || latestRegistration.value?.address_en
        || '-',
      editable: true,
      field: 'address',
    },
  ]
  return list
})


const infoPanels = computed(() => [
  {
    key: 'base',
    title: '基本信息',
    subtitle: '',
    list: baseInfoList.value,
  },
])

const profileInitial = computed(() => {
  if (!displayName.value || displayName.value === '-')
    return '-'
  return displayName.value.slice(0, 1).toUpperCase()
})


function startEditByKey(key: string) {
  const target = baseInfoList.value.find(item => item.key === key)
  if (target)
    startEdit(target)
}

// 开始编辑
function startEdit(item: any) {
  if (!item.editable)
    return

  editingField.value = item.key
  editForm.value = {
    value: item.value === '-' ? '' : item.value,
    field: item.field,
    label: item.label,
  }

  // 如果是手机号，需要验证码
  if (item.key === 'phone') {
    editForm.value.verificationcode = ''
    editForm.value.newPhone = editForm.value.value
  }
  
  // 如果是邮箱，需要验证码
  if (item.key === 'email') {
    editForm.value.emailVerificationcode = ''
  }

  // 如果是性别，需要转换值
  if (item.key === 'gender') {
    const detail = latestRegistration.value || {}
    editForm.value.value = detail.gender || ''
  }
}

// 取消编辑
function cancelEdit() {
  editingField.value = null
  editForm.value = {}
}

// 发送验证码
async function sendSmsCode() {
  if (!editForm.value.newPhone) {
    message.warning('请输入手机号')
    return
  }

  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(editForm.value.newPhone)) {
    message.warning('请输入正确的手机号')
    return
  }

  try {
    smsCodeLoading.value = true
    const response = (await sendSmsCodeApi({
      phone: editForm.value.newPhone,
      ttl_seconds: 300,
    })) as any

    if (response?.code === 0) {
      message.success('验证码已发送')
      smsCodeCountdown.value = 60
      const timer = setInterval(() => {
        smsCodeCountdown.value--
        if (smsCodeCountdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    }
    else {
      message.error(response?.message || response?.msg || '发送验证码失败')
    }
  }
  catch (error: any) {
    message.error(error?.message || error?.msg || '发送验证码失败')
  }
  finally {
    smsCodeLoading.value = false
  }
}

// 发送邮箱验证码
async function sendEmailCode() {
  if (!editForm.value.value) {
    message.warning('请输入邮箱地址')
    return
  }

  const emailRegex = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/
  if (!emailRegex.test(editForm.value.value)) {
    message.warning('请输入正确的邮箱地址')
    return
  }

  try {
    emailCodeLoading.value = true
    // TODO: 调用发送邮箱验证码API
    // const response = await sendEmailCodeApi({
    //   email: editForm.value.value,
    //   ttl_seconds: 300,
    // })
    
    // 模拟发送成功
    message.success('验证码已发送到您的邮箱，请查收')
    emailCodeCountdown.value = 60
    const timer = setInterval(() => {
      emailCodeCountdown.value--
      if (emailCodeCountdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  }
  catch (error: any) {
    message.error(error?.message || error?.msg || '发送验证码失败')
  }
  finally {
    emailCodeLoading.value = false
  }
}

// 保存编辑
async function saveEdit() {
  if (!latestRegistration.value?.id) {
    message.warning('无法找到报名信息，无法修改')
    return
  }

  // 验证必填项
  if (!editForm.value.value || editForm.value.value.trim() === '') {
    message.warning(`请输入${editForm.value.label}`)
    return
  }

  // 手机号特殊验证
  if (editForm.value.field === 'phone') {
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(editForm.value.newPhone)) {
      message.warning('请输入正确的手机号')
      return
    }
    if (!editForm.value.verificationcode) {
      message.warning('请输入验证码')
      return
    }
  }

  // 邮箱验证
  if (editForm.value.field === 'email') {
    const emailRegex = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/
    if (!emailRegex.test(editForm.value.value)) {
      message.warning('请输入正确的邮箱地址')
      return
    }
    if (!editForm.value.emailVerificationcode) {
      message.warning('请输入邮箱验证码')
      return
    }
  }

  try {
    editLoading.value = true

    const updateData: any = {
      id: latestRegistration.value.id,
      [editForm.value.field]: editForm.value.field === 'phone' ? editForm.value.newPhone : editForm.value.value,
    }

    // 如果是手机号，需要验证码
    if (editForm.value.field === 'phone') {
      updateData.verificationcode = editForm.value.verificationcode
    }
    
    // 如果是邮箱，需要验证码
    if (editForm.value.field === 'email') {
      updateData.emailVerificationcode = editForm.value.emailVerificationcode
    }

    const response = await updateRegistrationApi(updateData)

    if (response?.code === 0) {
      Modal.info({
        title: '提示',
        content: h('div', { style: 'font-size:16px; line-height:24px; color:#333;' }, '修改成功'),
        icon: h(CheckCircleOutlined, { style: 'color:#376d9b;' }),
        okText: '确定',
        okButtonProps: { style: { backgroundColor: '#376d9b', border: 'none', borderRadius: '0' } } as any,
        centered: true,
      })
      const savedField = editForm.value.field
      const savedValue = editForm.value.field === 'phone' ? editForm.value.newPhone : editForm.value.value
      
      editingField.value = null
      editForm.value = {}
      
      // 重新加载数据
      await fetchLatestRegistration()
      
      // 如果修改的是用户名，更新用户信息缓存
      if (savedField === 'username') {
        // 更新 localStorage 中的用户信息
        const userInfoStr = localStorage.getItem('userInfo')
        if (userInfoStr) {
          const localUserInfo = JSON.parse(userInfoStr)
          localUserInfo.userName = savedValue
          localStorage.setItem('userInfo', JSON.stringify(localUserInfo))
          // 更新 store 中的用户信息
          await userStore.getUserInfo()
        }
      }
    }
    else {
      message.error(response?.message || '修改失败')
    }
  }
  catch (error: any) {
    message.error(error?.message || '修改失败，请稍后重试')
  }
  finally {
    editLoading.value = false
  }
}

async function fetchLatestRegistration() {
  try {
    const response = (await getRegistrationsApi()) as any
    if (response?.code === 0 && Array.isArray(response.data) && response.data.length > 0) {
      const sorted = [...response.data].sort((a: any, b: any) => {
        const timeA = dayjs(a.registration_time)
        const timeB = dayjs(b.registration_time)
        return timeB.valueOf() - timeA.valueOf()
      })
      const latest = sorted[0]
      if (latest?.id) {
        const detailResp = (await getRegistrationDetailApi(String(latest.id))) as any
        if (detailResp?.code === 0 && detailResp.data) {
          latestRegistration.value = detailResp.data
        }
      }
    }
  }
  catch (error) {
    loadingFailed.value = true
    console.error('加载报名信息失败', error)
    message.error('加载考生信息失败，请稍后重试')
  }
}


onMounted(async () => {
  try {
    await userStore.getUserInfo()
  }
  catch (error) {
    console.error('加载用户信息失败', error)
  }
  finally {
    await fetchLatestRegistration()
    loading.value = false
  }
})
</script>

<template>
    <a-spin :spinning="loading">
      <div class="profile-hero ">
        <div class="hero-main">
          <div class="profile-avatar">
            <span>{{ profileInitial }}</span>
          </div>
          <div class="profile-info">
            <div class="name-row">
              <h1>{{ displayName }}</h1>
              <a-button
                v-if="baseInfoList.find(item => item.key === 'username')?.editable"
                type="link"
                size="small"
                class="ghost-link"
                @click="startEditByKey('username')"
              >
              </a-button>
            </div>
            <p v-if="displayCompany !== '-'" class="profile-company">
              {{ displayCompany }}
            </p>
            <div class="hero-contact">
              <div class="contact-item-horizontal">
                <span class="contact-label">手机号</span>
                <p class="contact-value">{{ displayPhone }}</p>
              </div>
              <div class="contact-item-horizontal">
                <span class="contact-label">邮箱</span>
                <p class="contact-value">{{ displayEmail }}</p>
              </div>
            </div>
          </div>
        </div>
     
              <div class="info-sections">
        <section
          v-for="panel in infoPanels"
          :key="panel.key"
          class="info-section"
        >
          <div class="section-head">
            <div>
              <h2>{{ panel.title }}</h2>
              <p>{{ panel.subtitle }}</p>
            </div>
          </div>
          <a-descriptions
            :column="2"
            class="compact-descriptions"
            layout="horizontal"
          >
            <a-descriptions-item
              v-for="item in panel.list"
              :key="item.key"
              :label="item.label"
            >
              <div class="description-item">
                <template v-if="editingField === item.key">
                  <template v-if="item.key === 'phone'">
                    <a-input
                      v-model:value="editForm.newPhone"
                      placeholder="请输入新手机号"
                      class="edit-input"
                    />
                    <div class="verification-code-wrapper">
                      <a-input
                        v-model:value="editForm.verificationcode"
                        placeholder="请输入验证码"
                        class="edit-input code-input"
                      />
                      <a-button
                        :loading="smsCodeLoading"
                        :disabled="smsCodeCountdown > 0"
                        @click="sendSmsCode"
                      >
                        {{ smsCodeCountdown > 0 ? `${smsCodeCountdown}秒后重试` : '获取验证码' }}
                      </a-button>
                    </div>
                  </template>
                  <template v-else-if="item.key === 'email'">
                    <a-input
                      v-model:value="editForm.value"
                      placeholder="请输入邮箱地址"
                      type="email"
                      class="edit-input"
                    />
                    <div class="verification-code-wrapper">
                      <a-input
                        v-model:value="editForm.emailVerificationcode"
                        placeholder="请输入邮箱验证码"
                        class="edit-input code-input"
                      />
                      <a-button
                        :loading="emailCodeLoading"
                        :disabled="emailCodeCountdown > 0"
                        @click="sendEmailCode"
                      >
                        {{ emailCodeCountdown > 0 ? `${emailCodeCountdown}秒后重试` : '发送验证码' }}
                      </a-button>
                    </div>
                  </template>
                  <template v-else-if="item.key === 'gender'">
                    <a-select
                      v-model:value="editForm.value"
                      placeholder="请选择性别"
                      class="edit-input"
                    >
                      <a-select-option :value="1">
                        Male
                      </a-select-option>
                      <a-select-option :value="2">
                        Female
                      </a-select-option>
                    </a-select>
                  </template>
                  <template v-else>
                    <a-input
                      v-model:value="editForm.value"
                      :placeholder="`请输入${item.label}`"
                      class="edit-input"
                    />
                  </template>
                  <div class="edit-actions">
                    <a-button
                      type="primary"
                      size="small"
                      :loading="editLoading"
                      @click="saveEdit"
                    >
                      保存
                    </a-button>
                    <a-button
                      size="small"
                      @click="cancelEdit"
                    >
                      取消
                    </a-button>
                  </div>
                </template>
                <template v-else>
                  <span class="description-value">{{ item.value === '-' ? '未填写' : item.value }}</span>
                  <a-button
                    v-if="item.editable"
                    type="link"
                    class="description-edit"
                    size="small"
                    @click="startEdit(item)"
                  >
                    <template v-if="item.key === 'phone'">
                      <EditOutlined />换手机号
                    </template>
                    <template v-else-if="item.key === 'email'">
                      <EditOutlined /> 验证邮箱
                    </template>
                    <template v-else>
                      <EditOutlined /> 修改
                    </template>
                  </a-button>
                </template>
              </div>
            </a-descriptions-item>
          </a-descriptions>
        </section>
      </div>
      </div>

    </a-spin>
</template>

<style scoped lang="less">
.account-settings {
  padding: 20px;
  min-height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
}

.profile-hero {
  overflow-y: scroll;
  height: 89vh;
  padding: 15px 10px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-bottom: 24px;
}


.hero-main {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}

.profile-avatar {
  width: 72px;
  height: 72px;
  border-radius: 50%;
  background: linear-gradient(145deg, #1c446b, #2b6da6);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  font-weight: 600;
}

.profile-info {
  font-size:16px;
  flex: 1;
}

.name-row {
  display: flex;
  align-items: center;
  gap: 12px;
}

.name-row h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #0f2a51;
}

.ghost-link {
  padding: 0;
  height: auto;
  color: #1c5ca6;
  font-size:16px;

  &:hover {
    color: #0a3c74;
  }
}

.profile-company {
  margin: 6px 0 0;
  color: #5d6e82;
}

.hero-contact {
  display: flex;
  gap: 24px;
  margin-top: 12px;
  flex-wrap: wrap;
}

.contact-item span {
  display: block;
  font-size: 14px;
  color: #8a96a8;
}

.contact-item p {
  margin: 4px 0 0;
  font-size: 16px;
  color: #1b2f4b;
}

.contact-item-horizontal {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.contact-item-horizontal .contact-label {
  font-size: 14px;
  color: #8a96a8;
  display: block;
}

.contact-item-horizontal .contact-value {
  margin: 0;
  font-size: 16px;
  color: #1b2f4b;
  display: block;
}

.hero-extra {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 12px;
}

.extra-item {
  padding: 12px 16px;
  border-radius: 12px;
  border: 1px solid rgba(28, 68, 107, 0.1);
  background: linear-gradient(135deg, rgba(55, 109, 155, 0.08), rgba(255, 255, 255, 0.6));
}

.extra-item span {
  font-size: 15px;
  color: #6a7e98;
}

.extra-item p {
  margin: 6px 0 0;
  font-size: 18px;
  font-weight: 600;
  color: #0d2442;
}

.hero-actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.stats-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  padding: 18px;
  border-radius: 16px;
}

.stat-label {
  font-size: 15px;
  color: #6b7c94;
}

.stat-value {
  margin-top: 6px;
  font-size: 22px;
  font-weight: 600;
  color: #173357;
}

.stat-desc {
  margin-top: 4px;
  font-size: 13px;
  color: #8a96a8;
}

.info-sections {
  display: flex;
  flex-direction: column;
  gap: 28px;
  margin-left: 13px;
}

.info-section {
  padding-bottom: 8px;
  border-bottom: 1px solid rgba(28, 68, 107, 0.08);
}

.section-head h2 {
  margin: 0;
  font-size: 20px;
  color: #173357;
}

.section-head p {
  margin: 4px 0 0;
  color: #7a889c;
}

.compact-descriptions {
  margin-top: 12px;

  :deep(.ant-descriptions-item-label) {
    width: 140px;
    font-weight: 500;
    color: #1c4b78;
  }

  :deep(.ant-descriptions-item-content) {
    color: #1b2f4b;
  }
}

.description-item {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.description-value {
  color: #1b2f4b;
}

.description-edit {
  padding: 0;
  height: auto;
  color: #1c5ca6;

  &:hover {
    color: #0a3c74;
  }
}

.edit-input {
  margin-bottom: 12px;
  width: 100%;
}

.verification-code-wrapper {
  display: flex;
  gap: 8px;
  align-items: flex-start;

  .code-input {
    flex: 1;
    margin-bottom: 0;
  }

  .ant-btn {
    white-space: nowrap;
    flex-shrink: 0;
  }
}

.edit-actions {
  display: flex;
  gap: 8px;
  margin-top: auto;
}

@media (max-width: 768px) {
  .account-settings {
    padding: 16px;
    height: auto;
    overflow-y: visible;
  }

  .hero-main {
    flex-direction: column;
    align-items: flex-start;
  }

  .hero-actions {
    flex-direction: column;
    width: 100%;
  }

  .hero-actions .ant-btn {
    width: 100%;
  }

  .info-sections {
    margin-left: 0;
  }

  .info-grid {
    grid-template-columns: 1fr;
  }
}
</style>
